<template>
  <div class="car-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
            v-model="searchForm.cname"
            placeholder="请输入车辆名称"
            clearable
            @keyup.enter.native="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 车辆列表 -->
    <el-card v-loading="loading">
      <el-row :gutter="20" class="car-grid">
        <el-col 
          v-for="car in carList" 
          :key="car.cid" 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6"
        >
          <el-card :body-style="{ padding: '0px' }" class="car-card">
            <div class="car-image">
              <el-image
                :src="getImageUrl(car.cimg)"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
            
            <div class="car-info">
              <h3 class="car-name">{{ car.cname }}</h3>
              <div class="car-desc">{{ car.cinfo }}</div>
              <div class="car-price">
                <span class="price">¥{{ car.crent }}</span>
                <span class="unit">/天</span>
              </div>
              
              <div class="car-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleRent(car)"
                  :disabled="car.status !== 1"
                >
                  {{ car.status === 1 ? '立即租车' : '已出租' }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="!loading && carList.length === 0" description="暂无车辆信息"></el-empty>
    </el-card>

    <!-- 租车对话框 -->
    <el-dialog
      title="确认租车"
      :visible.sync="rentDialog.visible"
      width="400px"
    >
      <div class="rent-form">
        <div class="car-info">
          <p>车辆名称：{{ rentDialog.car?.cname }}</p>
          <p>租金：¥{{ rentDialog.car?.crent }}/天</p>
        </div>
        <el-form :model="rentDialog.form" label-width="100px">
          <el-form-item label="取车时间">
            <el-date-picker
              v-model="rentDialog.form.takeTime"
              type="datetime"
              placeholder="选择取车时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="{
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7;
                }
              }"
            />
          </el-form-item>
          <el-form-item label="还车时间">
            <el-date-picker
              v-model="rentDialog.form.getTime"
              type="datetime"
              placeholder="选择还车时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="{
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7;
                }
              }"
            />
          </el-form-item>
        </el-form>
        <el-alert
          title="请确认租车信息并选择租期"
          type="warning"
          :closable="false"
          show-icon
        >
        </el-alert>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rentDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRent" :loading="rentDialog.loading">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CarList',
  
  data() {
    return {
      searchForm: {
        cname: ''
      },
      carList: [],
      loading: false,
      rentDialog: {
        visible: false,
        loading: false,
        car: null,
        form: {
          takeTime: '',
          getTime: ''
        }
      }
    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    // 获取车辆列表
    async fetchData() {
      this.loading = true
      try {
        const res = await request.get('/CarSearchServlet', {
          params: {
            cname: this.searchForm.cname || ''
          }
        })
        
        console.log('API响应:', res) // 调试日志
        
        if (res.code === 0) {
          if (Array.isArray(res.data)) {
            this.carList = res.data
            console.log('车辆列表:', this.carList) // 调试日志
          } else {
            console.error('返回的数据不是数组:', res.data)
            this.carList = []
          }
        } else {
          this.$message.error(res.msg || '获取车辆列表失败')
        }
      } catch (error) {
        console.error('获取车辆列表失败:', error)
        this.$message.error('获取车辆列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.fetchData()
    },

    // 租车
    handleRent(car) {
      this.rentDialog.car = car
      this.rentDialog.visible = true
    },

    // 确认租车
    async confirmRent() {
      if (!this.rentDialog.car) return
      
      // 检查登录状态
      const email = localStorage.getItem('email')
      if (!email) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }

      // 验证日期选择
      if (!this.rentDialog.form.takeTime || !this.rentDialog.form.getTime) {
        this.$message.warning('请选择取车和还车时间')
        return
      }

      // 验证日期顺序
      if (new Date(this.rentDialog.form.takeTime) >= new Date(this.rentDialog.form.getTime)) {
        this.$message.warning('还车时间必须晚于取车时间')
        return
      }
      
      this.rentDialog.loading = true
      try {
        // 创建订单
        const orderRes = await request.get('/PutOrderServlet', {
          params: {
            cid: this.rentDialog.car.cid,
            crent: this.rentDialog.car.crent,
            takeTime: this.rentDialog.form.takeTime,
            getTime: this.rentDialog.form.getTime,
            email: email,
            cname: this.rentDialog.car.cname
          }
        })
        
        if (orderRes.code === 0) {
          // 更新车辆状态为已出租
          await request.get('/CarChangeStatusServlet', {
            params: {
              cid: this.rentDialog.car.cid,
              status: 1  // 1 变为 -1，表示已出租
            }
          })
          
          this.$message.success('租车成功')
          this.rentDialog.visible = false
          this.fetchData()  // 刷新列表
        } else {
          this.$message.error(orderRes.msg || '租车失败')
        }
      } catch (error) {
        console.error('租车失败:', error)
        this.$message.error('租车失败')
      } finally {
        this.rentDialog.loading = false
      }
    },

    // 修改图片URL处理方法
    getImageUrl(cimg) {
      if (!cimg) {
        return require('@/assets/images/car-default.jpg')
      }
            
      // 拼接完整路径
      return `http://localhost:8080/exam_war/${cimg}`
    }
  }
}
</script>

<style lang="less" scoped>
.car-list {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f0f2f5;

  .search-card {
    margin-bottom: 20px;
  }

  .car-grid {
    display: flex;
    flex-wrap: wrap;
    margin: -10px;
  }

  .car-card {
    flex: 1;
    min-width: 280px;
    margin: 10px;
    transition: all 0.3s;
    background-color: #fff;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }

    .car-image {
      height: 200px;
      overflow: hidden;
      background-color: #f5f7fa;

      .el-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        color: #909399;
        font-size: 30px;
      }
    }

    .car-info {
      padding: 14px;

      .car-name {
        margin: 0;
        font-size: 16px;
        color: #303133;
        font-weight: bold;
      }

      .car-desc {
        margin: 8px 0;
        font-size: 14px;
        color: #909399;
        height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .car-price {
        margin: 8px 0;
        
        .price {
          font-size: 20px;
          color: #f56c6c;
          font-weight: bold;
        }
        
        .unit {
          font-size: 14px;
          color: #909399;
          margin-left: 4px;
        }
      }

      .car-actions {
        margin-top: 12px;
        text-align: right;
      }
    }
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
}

.rent-form {
  .car-info {
    margin-bottom: 20px;
    
    p {
      margin: 8px 0;
      font-size: 14px;
      color: #606266;
    }
  }
}
</style> 